package com.ruoyi.framework.handler;


import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

/**
 * @Description 默认数据库字段填充类
 * @Author huangxiong
 * @Date 2022/7/8 14:21
 * @Version V1.0
 */
public class DefaultDBFieldHandler implements MetaObjectHandler {


    private static String CREATE_TIME = "createTime";
    private static String UPDATE_TIME = "updateTime";

    private static String CREATE_BY = "createBy";
    private static String UPDATE_BY = "updateBy";


    @Override
    public void insertFill(MetaObject metaObject) {
        if(validator()) {
            return;
        }
        String username = SecurityUtils.getLoginUser().getUsername();
        mySetFieldValByName( CREATE_TIME, new Date(),metaObject);
        mySetFieldValByName( CREATE_BY, username,metaObject);
        mySetFieldValByName( UPDATE_TIME, new Date() ,metaObject);
        mySetFieldValByName( UPDATE_BY, username,metaObject);

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if(validator()) {
            return;
        }
        String username = SecurityUtils.getLoginUser().getUsername();
        mySetFieldValByName( UPDATE_TIME, new Date() ,metaObject);
        mySetFieldValByName( UPDATE_BY, username,metaObject);
    }

    /**
     *  校验是否注入
     * @return true : 不注入，false ： 注入
     */
    private boolean validator(){
        try {
            return SecurityUtils.getLoginUser() == null;
        }catch (Exception e){
            return true;
        }

    }

    private void mySetFieldValByName(String fieldName,Object fieldVal,MetaObject metaObject){
//        if(metaObject.hasSetter(fieldName) && Objects.isNull(metaObject.getValue(fieldName))){
        if(metaObject.hasSetter(fieldName)){
            setFieldValByName( fieldName, fieldVal,metaObject);
        }

    }

}
